package com.yunshu.yunshuapp.user;

import android.app.DatePickerDialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.android.gms.common.api.GoogleApiClient;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.yunshu.yunshuapp.NavigationBar;
import com.yunshu.yunshuapp.R;
import com.yunshu.yunshuapp.network.YSCallback;
import com.yunshu.yunshuapp.network.YSRequest;
import com.yunshu.yunshuapp.utils.YSUtils;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Calendar;

import me.iwf.photopicker.PhotoPicker;


public class UserInfoActivity extends AppCompatActivity implements Toolbar.OnMenuItemClickListener, View.OnClickListener {

    private String image;
    /**
     * ATTENTION: This was auto-generated to implement the App Indexing API.
     * See https://g.co/AppIndexing/AndroidStudio for more information.
     */
    private GoogleApiClient client;
    private String avatarUrl;
    private ImageLoader mImageLoader;
    private DisplayImageOptions options;
    private Button confirmBtn;
    private int year;
    private int month;
    private int day;
    private int sex;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_user_info);

        NavigationBar bar = (NavigationBar) findViewById(R.id.navigationBar);
        bar.putInActivity(this);
        bar.setTitle("个人信息");
        bar.setOnMenuItemClickListener(this);
        this.addListener();

        EditText phoneET = (EditText) this.findViewById(R.id.phoneET);
        phoneET.setEnabled(true);

        confirmBtn = (Button) findViewById(R.id.submitBtn);

        // 获取图片加载实例
        mImageLoader = ImageLoader.getInstance();
        options = YSUtils.displayImageOptions();

        this.refreshUI();

        //初始化Calendar日历对象
        Calendar mycalendar=Calendar.getInstance();
        year = mycalendar.get(Calendar.YEAR); //获取Calendar对象中的年
        month = mycalendar.get(Calendar.MONTH);//获取Calendar对象中的月
        day = mycalendar.get(Calendar.DAY_OF_MONTH);//获取这个月的第几天
    }

    private void addListener() {

        View view = findViewById(R.id.avatar);
        view.setOnClickListener(this);

        Button btn = (Button) findViewById(R.id.submitBtn);
        btn.setOnClickListener(this);

        TextView birthdayTV = (TextView) findViewById(R.id.birthdayTV);
        birthdayTV.setOnClickListener(this);

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_userinfo, menu);
        return true;
    }

    @Override
    public boolean onMenuItemClick(MenuItem item) {
        YSUser.logout();
        finish();
        return true;
    }


    private static final int PICTURE = 10086; //requestcode


    @Override
    public void onClick(View view) {

        if (view.getId() == R.id.avatar) {

            PhotoPicker.builder()
                    .setPhotoCount(1)
                    .setShowCamera(true)
                    .setShowGif(false)
                    .setPreviewEnabled(false)
                    .start(this, PhotoPicker.REQUEST_CODE);
        } else if (view.getId() == R.id.submitBtn) {
            YSUser user = this.collectInfo();
            user.update(new YSCallback(){

                @Override
                public void onResponse(int isSuccess, JsonNode result) {
                    if (isSuccess == YSRequest.REQUEST_OK){
                        YSUtils.showToastOn( UserInfoActivity.this ,"修改成功！");
                        finish();
                    }else{
                        YSUtils.showToastOn( UserInfoActivity.this ,"修改失败，请稍后重试！");
                    }
                }
            }, this);
        }else if(view.getId() == R.id.birthdayTV){
            this.chooseBirthday();
        }
    }

    private void chooseBirthday(){

        //创建DatePickerDialog对象
        DatePickerDialog dpd=new DatePickerDialog(this,Datelistener,year,month,day);
        dpd.show();//显示DatePickerDialog组件
    }

    private DatePickerDialog.OnDateSetListener Datelistener=new DatePickerDialog.OnDateSetListener()
    {
        /**params：view：该事件关联的组件
         * params：myyear：当前选择的年
         * params：monthOfYear：当前选择的月
         * params：dayOfMonth：当前选择的日
         */
        @Override
        public void onDateSet(DatePicker view, int myyear, int monthOfYear, int dayOfMonth) {


            //修改year、month、day的变量值，以便以后单击按钮时，DatePickerDialog上显示上一次修改后的值
            int year = myyear;
            int month = monthOfYear;
            int day = dayOfMonth;
            //更新日期
            updateDate(year, month,day);

        }

    };

    private void updateDate(int year, int month, int day) {

        String date = year + "-" + month + "-" +day;

        TextView birthdayTV = (TextView) findViewById(R.id.birthdayTV);
        birthdayTV.setText(date);

    }

    private YSUser collectInfo() {

        YSUser user = new YSUser();
        user.setAvatarUrl(this.avatarUrl);

        EditText nameET = (EditText) this.findViewById(R.id.nameET);
        user.setName( nameET.getText().toString() );

        EditText phoneET = (EditText) this.findViewById(R.id.phoneET);
        user.setPhone( phoneET.getText().toString() );

        EditText qqET = (EditText) this.findViewById(R.id.qqET);
        user.setQq( qqET.getText().toString() );

        EditText wechatET = (EditText) this.findViewById(R.id.wechatET);
        user.setWx( wechatET.getText().toString() );

        EditText companyET = (EditText) this.findViewById(R.id.companyET);
        user.setCompany( companyET.getText().toString() );

        EditText positionET = (EditText) this.findViewById(R.id.positionET);
        user.setPosition( positionET.getText().toString() );

        EditText emailET = (EditText) this.findViewById(R.id.emailET);
        user.setEmail( emailET.getText().toString() );

        TextView birthdayTV = (TextView) this.findViewById(R.id.birthdayTV);
        user.setBirthday( birthdayTV.getText().toString() );

        TextView sexTV = (TextView) this.findViewById(R.id.sexTV);
        String sex = sexTV.getText().toString();
        if (sex.contains("男"))
            user.setSex(1);
        else if (sex.contains("女"))
            user.setSex(2);
        else
            user.setSex(0);


        user.setUid(YSUser.instance().getUid());
//        EditText birthdayET = (EditText) this.findViewById(R.id.);
//        user.setName( birthdayET.getText().toString() );
//        params.put("icon",user.getAvatarUrl());
//        params.put("name",user.getName());
//        params.put("qq",user.getQq());
//        params.put("wx",user.getWx());
//        params.put("company",user.getCompany());
//        params.put("position",user.getPosition());
//        params.put("email",user.getEmail());
//        params.put("birthday",user.getBirthday());
//        params.put("sex",""+user.getSex());


        return user;
    }

    private void refreshUI() {
        YSUser user = YSUser.instance();
        ImageView avatarImg = (ImageView) findViewById(R.id.head_icon);
        avatarUrl = user.getAvatarUrl();
        mImageLoader.displayImage(user.getAvatarUrl(), avatarImg);

        EditText nameET = (EditText) this.findViewById(R.id.nameET);
        if (user.getName() != null)
            nameET.setText(user.getName());

        EditText phoneET = (EditText) this.findViewById(R.id.phoneET);
        if (user.getPhone() != null)
            phoneET.setText(user.getPhone());

        EditText qqET = (EditText) this.findViewById(R.id.qqET);
        if (user.getQq() != null)
            qqET.setText(user.getQq());

        EditText wechatET = (EditText) this.findViewById(R.id.wechatET);
        if (user.getWx() != null)
            wechatET.setText(user.getWx());

        EditText companyET = (EditText) this.findViewById(R.id.companyET);
        if (user.getCompany() != null)
            companyET.setText(user.getCompany());

        EditText positionET = (EditText) this.findViewById(R.id.positionET);
        if (user.getPosition() != null)
            positionET.setText(user.getPosition());

        EditText emailET = (EditText) this.findViewById(R.id.emailET);
        if (user.getEmail() != null)
            emailET.setText(user.getEmail());

        TextView birthdayTV = (TextView) this.findViewById(R.id.birthdayTV);
        if (user.getBirthday() != null)
            birthdayTV.setText(user.getBirthday());

        TextView setTV = (TextView) this.findViewById(R.id.sexTV);
        if (user.getSex() == 0){
            setTV.setText("未设置");
        }else if(user.getSex() == 1){
            setTV.setText("男");
        }else if(user.getSex() == 2){
            setTV.setText("女");
        }
        sex = user.getSex();
    }

    @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (resultCode == RESULT_OK && requestCode == PhotoPicker.REQUEST_CODE) {
            if (data != null) {
                ArrayList<String> photos =
                        data.getStringArrayListExtra(PhotoPicker.KEY_SELECTED_PHOTOS);
                String photoPath = photos.get(0);
                this.uploadImage(photoPath);
            }
        }
    }

    private void uploadImage(String photoPath) {

        Bitmap img = BitmapFactory.decodeFile(photoPath);
        Bitmap newimg = Bitmap.createScaledBitmap(img, 100, 100, true);
        this.confirmBtn.setBackgroundColor(YSUtils.getColor(R.color.colorPrimaryDark,this));

        this.confirmBtn.setEnabled(false);
        new YSRequest(this).uploadImg(photoPath,newimg, new YSCallback() {
            @Override
            public void onResponse(int isSuccess, JsonNode json) {
//                {"code":1,"result":"{\"img\":\"http://60.205.225.113/pictureService/showImage.action?type=0&filename=5a0313c5-9f3e-4788-8e25-c7d60f3e9fda.png\"}","msg":"上传成功"}
                ObjectMapper mapper = new ObjectMapper();
                try {
                    JsonNode resultNode = mapper.readTree(json.textValue());
                    JsonNode imgNode = resultNode.get("img");
                    if (imgNode != null){
                        avatarUrl = imgNode.asText();
                        displayImage(avatarUrl);
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }finally {
                    reenableButton();
                }
            }
        });
    }

    private void displayImage(final String imageURL){

        runOnUiThread(new Runnable() {
                          @Override
                          public void run() {
                              ImageView avatarImg = (ImageView) findViewById(R.id.head_icon);
                              mImageLoader.displayImage(imageURL, avatarImg);
                          }
                      });
    }

    private void reenableButton() {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                confirmBtn.setEnabled(true);
                confirmBtn.setBackgroundColor(YSUtils.getColor(R.color.colorPrimary, UserInfoActivity.this));

                ImageView avatarImg = (ImageView) findViewById(R.id.head_icon);
                mImageLoader.displayImage(avatarUrl, avatarImg);
            }
        });
    }
}
